package com.lwl.crm.settings.web.controller;

import com.lwl.crm.exception.LoginException;
import com.lwl.crm.settings.entity.User;
import com.lwl.crm.settings.service.UserService;
import com.lwl.crm.settings.service.impl.UserServiceImpl;
import com.lwl.crm.utils.PrintJson;
import com.lwl.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * user的登录功能
 */
public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //访问该service一定会执行该方法,即在定位/settings/user/login.do
        login(req,resp);
        if("/settings/user/login.do".equals(req.getServletPath())
                || "/settings/user/login.html".equals(req.getServletPath())) {
            login(req,resp);
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) {
        //获取访问ip
        String ip = req.getRemoteAddr();
        //通过动态代理获取UserService的动态代理对象
        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());
        try {
            //调用service层的业务功能
            User user = userService.login(req.getParameter("loginAct"),
                    req.getParameter("loginPwd"),
                    ip);
            //将信息保存到request域中
            req.setAttribute("user",user);
            //将成功的信息以json形式返回前端
            System.out.println("-------------------");
            PrintJson.printJsonFlag(resp,true);
        } catch (LoginException e) {
            e.printStackTrace();
            //拦截异常消息
            String msg = e.getMessage();
            //封装异常的信息
            Map<String,Object> map = new HashMap<>();
            map.put("success",true);
            map.put("msg",msg);
            //将信息以json形式返回前端
            PrintJson.printJsonObj(resp,msg);
        }
    }
}
